﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CueSheetLibrary;
using CueMounter.DokanStructure;

namespace CueMounter {
	class DokanCueSheetFile : DokanFile {
		public CueSheet Sheet;
		public int Index;
		public WaveFile File;

		public DokanCueSheetFile(CueSheet sheet, int index) {
			Sheet = sheet;
			Index = index;

			IWaveProvider waveProvider = WaveProviderFactory.GetWaveProvider(sheet.Filename);

			if(TrackEndFrames == 0) {
				waveProvider.SetSpanFrames(TrackStartFrames, 0);
			} else {
				waveProvider.SetSpanFrames(TrackStartFrames, TrackEndFrames - TrackStartFrames);
			}

			File = new WaveFile(waveProvider);

			Name = MakeFileName(index);
		}

		private long TrackStartFrames {
			get {
				return Sheet.Tracks[Index].GetIndex(1);
			}
		}

		private long TrackEndFrames {
			get {
				if(Index < Sheet.Tracks.Length - 1) {
					return Sheet.Tracks[Index + 1].GetIndex(1);
				} else {
					return 0;
				}
			}
		}

		public override void Dispose() {
			File.Dispose();
			File = null;
		}

		private string MakeFileName(int index) {
			return (index + 1).ToString("00") + ". " +
				Sheet.Tracks[index].TitleLatinOnly
					.Replace("\t", "")
					.Replace("|", "-")
					.Replace(":", " -")
					.Replace("/", " - ")
					.Replace("*", "")
					.Replace("<", "")
					.Replace(">", "")
					.Replace("<", "")
					.Replace("?", "")
					.Replace("\"", "")
                    .Trim() +
				".wav";
		}

		public override long Length {
			get {
				return File.Length;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public override bool CanRead { get { return true; } }

		public override long Read(long offset, byte[] buffer, long bufferOffset, long length) {
			return File.Read((int)offset, buffer, (int)bufferOffset, (int)length);
		}

		public TimeSpan TrackLength {
			get {
				return File.WaveProvider.BytesToTime(File.WaveProvider.LengthBytes);
			}
		}

		public TimeSpan TrackStart {
			get {
				return File.WaveProvider.BytesToTime(File.WaveProvider.StartBytes);
			}
		}
	}
}
